package com.xiaoyy.app.extend.util;
import com.aliyun.dysmsapi20170525.Client;
import com.xiaoyy.core.common.exception.AppException;
import com.xiaoyy.core.common.vo.AliyunVO;
import com.aliyun.dysmsapi20170525.models.*;
import com.aliyun.teaopenapi.models.*;
import org.apache.commons.lang3.StringUtils;
public class AliyunUtil {

    /**
     * 使用AK&SK初始化账号Client
     * @param accessKeyId
     * @param accessKeySecret
     * @return Client
     * @throws Exception
     */
    public static Client createClient(String accessKeyId, String accessKeySecret) throws Exception {
        Config config = new Config()
                // 您的AccessKey ID
                .setAccessKeyId(accessKeyId)
                // 您的AccessKey Secret
                .setAccessKeySecret(accessKeySecret);
        // 访问的域名
        config.endpoint = "dysmsapi.aliyuncs.com";
        return new Client(config);
    }

    /**
     * 发送阿里云短信
     * @param aliyunVO
     * @return
     */
    public static void  sendMsg(AliyunVO aliyunVO){
        if(StringUtils.isEmpty(aliyunVO.getAccessKeyId())){
            throw new AppException("阿里云 API 的密钥Id不能为空");
        }
        if(StringUtils.isEmpty(aliyunVO.getAccessKeySecret())){
            throw new AppException("阿里云 API 的密钥不能为空");
        }
        // 复制代码运行请自行打印 API 的返回值
        try {
            //发起发送短信请求
            com.aliyun.dysmsapi20170525.Client client = AliyunUtil.createClient(aliyunVO.getAccessKeyId(), aliyunVO.getAccessKeySecret());
            SendSmsRequest sendSmsRequest = new SendSmsRequest();
            // 复制代码运行请自行打印 API 的返回值
            sendSmsRequest.setPhoneNumbers(aliyunVO.getPhoneNumbers());
            sendSmsRequest.setSignName(aliyunVO.getSignName());
            sendSmsRequest.setTemplateCode(aliyunVO.getTemplateCode());
            //参数设置到短信参数中
            if(!StringUtils.isEmpty(aliyunVO.getTemplateParam())){
                sendSmsRequest.setTemplateParam(aliyunVO.getTemplateParam());
            }
            client.sendSms(sendSmsRequest);
        } catch (Exception e) {
            e.printStackTrace();
            throw new AppException("短信发送失败");
        }

    }
}
